package pl.wroc.uni.ii.puzzle.view;

import pl.wroc.uni.ii.puzzle.game.Game;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;

public class GameView extends View {

	private Game game;

	public GameView(Context context, String hardship) {
		super(context);
		setOnTouchListener(new SwipeDetector());
		game = new Game(context, hardship);
		
		post(new Runnable() {
			@Override
			public void run() {
				game.start();			
			}
		});
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		game.draw(canvas);
	}
	
	private class SwipeDetector implements OnTouchListener {
	    private static final int MIN_DISTANCE = 20;
	    private float downX, downY, upX, upY;

	    @Override
	    public boolean onTouch(View v, MotionEvent event) {
	        switch(event.getAction()){
	        case MotionEvent.ACTION_DOWN: {
	            downX = event.getX();
	            downY = event.getY();
	            return true;
	        }
	        case MotionEvent.ACTION_UP: {
	            upX = event.getX();
	            upY = event.getY();

	            float deltaX = downX - upX;
	            float deltaY = downY - upY;

	            // swipe horizontal?
	            if(Math.abs(deltaX) > MIN_DISTANCE){
	                // left or right
	                if(deltaX < 0) { game.onLeftToRightSwipe(v, downX, downY); return true; }
	                if(deltaX > 0) { game.onRightToLeftSwipe(v, downX, downY); return true; }
	            }
	            // swipe vertical?
	            else if(Math.abs(deltaY) > MIN_DISTANCE){
	                // top or down
	                if(deltaY < 0) { game.onTopToBottomSwipe(v, downX, downY); return true; }
	                if(deltaY > 0) { game.onBottomToTopSwipe(v, downX, downY); return true; }
	            }
	            else {
	                game.onClick(v, downX, downY); return true;
	            }
	        }
	        }
	        return false;
	    }
	}
}